<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Http\Models\UserAmountLog;
use App\Http\Models\ZtkAdv;
use App\Http\Models\ZtkUser;
use App\Http\Models\ZtkUserAutoOrder;
use App\Library\Response;
use App\Service\OSS;
use App\Validate\Web\UserUpdateValidate;
use App\Validate\Web\UserRepassValidate;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{

    const CLASS_NAME = [1 => '充值', 2 => '发起提现', 3 => '取消提现退回', 4 => '管理人取消提现退回', 5 => '发布任务', 6 => '完成任务', 7 => '任务退回', 8=>'发布广告', 9=>'未完成任务罚款'];


    public function home()
    {
        return view('web.user.home');
    }

    public function set()
    {
        $user = ZtkUser::find(Auth::id());
        return view('web.user.set',['user' => $user]);
    }

    public function recharge()
    {
        return view('web.user.recharge');
    }

    public function withdraw()
    {
        return view('web.user.withdraw');
    }

    public function incomeExpend()
    {
        return view('web.user.incomeExpend');
    }

    /**
     * 已认证联盟
     */
    public function union()
    {
        $list = ZtkUser::where('is_union_auth','>',0)->orderBy('sorting','asc')->orderBy('is_union_auth','desc')
            ->select('id','avatar','union_name','union_desc','is_union_auth')
            ->paginate(20000);
        return view('web.user.union',['list' => $list]);
    }

    /**
     * 修改用户信息
     * @param Request $request
     * @return mixed
     */
    public function update(Request $request)
    {
        $validate = new UserUpdateValidate($request);
        if (!$validate->goCheck()) {
            return Response::response(['code' => Response::PARAM_ERROR, 'msg' => $validate->errors->first()]);
        }
        $status = $request->input('auto_status') ?? 0;

        try {
            $data = $request->only([
                'name','receive_order_price','union_desc'
            ]);
            ZtkUser::where('id',Auth::id())->update($data);

            ZtkUserAutoOrder::where('user_id',Auth::id())->update(['status'=>$status]);

            return Response::response(['code' => Response::OK, 'msg' => '修改成功']);
        } catch (QueryException $e) {
            return Response::response(['code' => Response::SQL_ERROR, 'msg' => '修改失败']);
        }
    }

    /**
     * 修改密码
     * @param Request $request
     * @return mixed
     */
    public function repass(Request $request)
    {
        $validate = new UserRepassValidate($request);
        if (!$validate->goCheck()) {
            return Response::response(['code' => Response::PARAM_ERROR, 'msg' => $validate->errors->first()]);
        }

        try {
            $password = $request->input('password');

            $data = [
                'password'  =>bcrypt($password),
            ];

            ZtkUser::where('id',Auth::id())->update($data);

            Auth::logout();
            return Response::response(['code' => Response::OK, 'msg' => '密码修改成功,请重新登录','data' => ['action' => route('login')]]);
        } catch (QueryException $e) {
            return Response::response(['code' => Response::SQL_ERROR, 'msg' => '修改失败']);
        }
    }


    /**
     * 上传头像
     */
    public function updateAvatar(Request $request)
    {
        $imageUrl = OSS::uploadImage($request,'avatar');
        if (!$imageUrl){
            return Response::response(['code' => Response::BAD_REQUEST, 'msg' => '头像上传失败']);
        }

        try {
            $data = [
                'avatar'  => $imageUrl,
            ];
            ZtkUser::where('id',Auth::id())->update($data);

            return Response::response(['code' => Response::OK, 'msg' => '头像上传成功','data' => ['imageUrl'=>$imageUrl]]);
        } catch (QueryException $e) {
            return Response::response(['code' => Response::SQL_ERROR, 'msg' => '头像上传失败']);
        }
    }


    /**
     * 联盟列表
     */
    public function unionList(Request $request)
    {
        $page = $request->input('page',1);
        $limit = $request->input('limit',50);
        $type = $request->input('type',2); //1=普通单黑名单 2=指派联盟

        if($type == 1){
            $black = ZtkUser::where('id',Auth::id())->where('black_status',1)->exists();
            if(!$black)return Response::response(['code' => Response::SQL_ERROR, 'msg' => '您没有添加黑名单的权限，请直接发布任务或联系管理员！']);
        }
        $results = ZtkUser::where('is_union_auth','>',0)->paginate($limit, ['id','union_name','receive_order_price'], 'page', $page);
        $results->transform(function ($item){
            $item['offer_price'] = $item->receive_order_price;
            return $item;
        });

        return Response::response(['code' => Response::OK, 'msg' => 'SUCCESS', 'data' => $results->items(), 'count' => $results->total()]);
    }

    /**
     * 收支明细
     */
    public function amountLogList(Request $request)
    {
        $page = $request->input('page',1);
        $limit = $request->input('limit',10);

        $results = UserAmountLog::where('class','<>',9)
            ->where('user_id',Auth::id())
            ->orderByDesc('id')->paginate($limit, ['*'], 'page', $page);

        $results->transform(function ($item) {
            $item['class_name'] = self::CLASS_NAME[$item->class];
            return $item;
        });

        return Response::response(['code' => Response::OK, 'msg' => 'SUCCESS', 'data' => $results->items(), 'count' => $results->total()]);
    }


    //我的广告
    public function adv()
    {
        return view('web.user.adv');
    }

    /**
     * 发布广告
     * @param Request $request
     * @return
     */
    public function pubAdv(Request $request)
    {
        $input = $request->all();
        $validate = Validator::make($input, [
            'day' => 'required|integer|min:30',
            'text' => 'required|string',
            'money' => 'required|numeric',
        ]);
        if ($validate->fails()) {
            return Response::response(['code' => 101, 'msg' => '参数有误']);
        }
        if($input['day'] % 30 != 0){return Response::response(['code' => 101, 'msg' => '展示天数必须是30的倍数']);}

        $user_id = Auth::id();
        $amount = $input['day']*$input['money'];
        $userMoney = ZtkUser::find($user_id)->amount ?? 0;
        if($amount > $userMoney){return Response::response(['code' => 101, 'msg' => '账户余额不足']);}

        DB::beginTransaction();
        try {

            ZtkAdv::create([
                'user_id' => $user_id,
                'text' => $input['text'],
                'money' => $input['money'],
                'day' => $input['day']
            ]);

            $user = ZtkUser::find($user_id);
            $user->decrement('amount', $amount);

            UserAmountLog::create([
                'user_id' => $user_id,
                'trade_no' => '',
                'amount' => $amount,
                'after_amount' => $user->amount,
                'type' => 2, //支出
                'class' => 8, //发布广告
            ]);

            DB::commit();

            return Response::response(['code' => Response::OK, 'msg' => '发布广告成功', 'data' => ['action' => url('user-adv')]]);
        } catch (QueryException $e) {
            DB::rollBack();
            return Response::response(['code' => Response::SQL_ERROR, 'msg' => '发布广告失败']);
        }
    }


    /**
     * 我的广告列表
     */
    public function myAdvList(Request $request)
    {
        //echo Auth::id();exit;
        $class = [1 => '待审核', 2 => '已通过', 3 => '已拒绝'];
        $page = $request->input('page',1);
        $limit = $request->input('limit',10);
        $results = ZtkAdv::where('user_id',Auth::id())->with('user')->orderByDesc('created_at')->paginate($limit, ['*'], 'page', $page);
        $results->transform(function ($item) use($class){
            $item['status'] = $class[$item->status];
            $item['end_date'] = $item->end_date > 0 ? Carbon::parse($item->end_date)->format('Y-m-d') : '';
            return $item;
        });

        return Response::response(['code' => Response::OK, 'msg' => 'SUCCESS', 'data' => $results->items(), 'count' => $results->total()]);
    }

    /**
     * 广告页面
     */
    public function advList(Request $request)
    {
        //echo Auth::id();exit;

        $date = date('Y-m-d');
        $results = ZtkAdv::where('status',2)->where('end_date','>',$date)->orderBy('sorting','asc')->limit(30)->get();

       // print_r($results);exit;
        return view('web.user.advlist',['list' => $results]);
    }

    //惩罚记录
    public function aFineList(Request $request)
    {

        $page = $request->input('page',1);
        $limit = $request->input('limit',10);
        $results = UserAmountLog::notDelete()->where('class',9)
            ->where('user_id',Auth::id())
            ->with('user','task.user')
            ->orderByDesc('created_at')->paginate($limit, ['*'], 'page', $page);

        $results->transform(function ($item) {
            $item['task_id'] = $item->task->id ?? '';
            $item['class_name'] = $item->task->title ?? ''; //self::CLASS_NAME[$item->class];
            return $item;
        });

        return Response::response(['code' => Response::OK, 'msg' => 'SUCCESS', 'data' => $results->items(), 'count' => $results->total()]);

    }



}
